using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Admin.NET.Application.DL645;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Application.Enums;
using Admin.NET.Application.GuangHeMeter;
using Admin.NET.Application.Mqtt.mqttresponse;
using Admin.NET.Application.Service.Electricity;
using Admin.NET.Application.Util;
using Admin.NET.Core;
using Furion.FriendlyException;
using Furion.Schedule;
using Microsoft.Extensions.DependencyInjection;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Formatter;
using Newtonsoft.Json;

namespace Admin.NET.Application.Job;

[JobDetail("job_readinternet", Description = "网线电表读取", GroupName = "default", Concurrent = false)]
[PeriodMinutes(50L, TriggerId = "trigger_readinternet", Description = "网线电表读取", RunOnStart = false)]
public class ReadMeterByInternetJob : IJob
{
	private readonly IServiceScopeFactory _scopeFactory;

	public ReadMeterByInternetJob(IServiceScopeFactory scopeFactory)
	{
		_scopeFactory = scopeFactory;
	}

	public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
	{
		using IServiceScope serviceScope = _scopeFactory.CreateScope();
		SqlSugarRepository<ElectricMeter> meterServer = serviceScope.ServiceProvider.GetService<SqlSugarRepository<ElectricMeter>>();
		List<ElectricMeter> listMeter = await (from u in meterServer.AsQueryable()
			where u.BrandId == 111 && u.SignalStatus == 1
			select u).ToListAsync();
		new DL645Agreement();
		Thread.Sleep(10000);
		foreach (ElectricMeter item in listMeter)
		{
			try
			{
				LoggerExtension.Info("开始集中超标块表" + item.Sn + "----" + item.LowAddr);
				(IAggrementPlugin, BrandModel) plugin = AggrementPluginUtil.GetPlugin(item);
				var (pluginService, _) = plugin;
				_ = plugin.Item2;
				Dictionary<string, UploadMqttInfo> dic = new Dictionary<string, UploadMqttInfo>();
				UploadMqttInfo uploadMqttInfo = new UploadMqttInfo();
				EPowerService ePowerService = new EPowerService();
				LoggerExtension.Info("开始集中超标块表总电量" + item.Sn + "----" + item.LowAddr);
				string allRotal = pluginService.ReadCombinedAllTotal(item.Sn, item.LowAddr, "");
				uploadMqttInfo.Alltotal = allRotal;
				LoggerExtension.Info("开始集中超标块表总电量结束" + item.Sn + "----" + item.LowAddr);
				DL645Agreement dL645 = new DL645Agreement();
				uploadMqttInfo.State = ParseDLT645Result(await pluginService.Transform(valueCmd: string.Join("", (from x in dL645.Send645Agreement(AgreementaType.Reading, item.LowAddr, "36383337").ToArray().ToArray()
					select x.ToString("x2")).ToArray()), imei: item.Sn));
				dic.Add(item.LowAddr, uploadMqttInfo);
				int newtype = 0;
				LoggerExtension.Info("开始上报数据" + item.Sn + "----" + item.LowAddr + JsonConvert.SerializeObject(dic));
				Console.WriteLine($"测试111111111111111111111{item.Sn}{newtype}{JsonConvert.SerializeObject(dic)}");
				MqttFactory factory = new MqttFactory();
				IMqttClient mqttClient = factory.CreateMqttClient();
				MqttClientOptions options = new MqttClientOptionsBuilder().WithTcpServer("119.3.246.97", 1883).WithProtocolVersion(MqttProtocolVersion.V500).WithClientId(Guid.NewGuid().ToString())
					.WithCleanSession(value: false)
					.WithKeepAlivePeriod(TimeSpan.FromSeconds(30.0))
					.WithCredentials("yuyao", "yuyao20210104")
					.Build();
				MqttClientConnectResult connectResult = mqttClient.ConnectAsync(options).Result;
				if (connectResult.ResultCode == MqttClientConnectResultCode.Success)
				{
					string byteData = "{\"r\":-55,\"d\":\"{\\\"AAAAAAAAAAAA\\\":{\\\"totalE\\\":\\\"" + uploadMqttInfo.Alltotal + "\\\",\\\"state\\\":\\\"" + uploadMqttInfo.State + "\\\"}}\",\"o\":5}";
					MqttApplicationMessage message = new MqttApplicationMessageBuilder().WithTopic("/iotinfo/meter/" + item.Sn).WithPayload(byteData).Build();
					mqttClient.PublishAsync(message).Wait();
					await mqttClient.DisconnectAsync();
					await ePowerService.MeterUpload(item.Sn, newtype, dic);
				}
			}
			catch (Exception ex)
			{
				LoggerExtension.Error("设备报错啦dingshi定时任务1", ex);
			}
		}
	}

	private string ParseDLT645Result(string body)
	{
		if (string.IsNullOrWhiteSpace(body))
		{
			return "";
		}
		List<byte> list = new List<byte>();
		list.Add(254);
		list.Add(254);
		list.Add(254);
		list.Add(254);
		bool sucess = true;
		for (int i = 0; i < body.Length / 2; i++)
		{
			byte byteInfo = (byte)Convert.ToInt32(body.Substring(i * 2, 2), 16);
			if (!(byteInfo == 254 && sucess))
			{
				sucess = false;
				list.Add(byteInfo);
			}
		}
		AgreementAnalysis resultInfo = DL645Agreement.DL645Analysis(list.ToArray());
		if (!resultInfo.Sucess)
		{
			throw Oops.Oh(ErrorCodeEnumEx.X1001);
		}
		if (!string.IsNullOrWhiteSpace(resultInfo.Data))
		{
			if (resultInfo.Data.Length > 8)
			{
				string infoType = resultInfo.Data.Substring(0, 8).ToUpper();
				string infoData = resultInfo.Data.Substring(8);
				return DL645ParameterSet.AnalisReading(infoType, infoData);
			}
			return "";
		}
		return "";
	}
}
